<?php

// 消息项目主动拉取（投资人）
// POST project.msg.pull

namespace app\api\resource\project\msg;
use think\Db;
use think\Session;

class Pull
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = ['login','isTzz','tzzCert'];
    // 描述
    public $_description = '消息项目主动拉取（投资人）';
    // 参数
    public $_param  = [
        'project_id' => '项目主键',
    ];
    // 返回
    public $_return = [
        201 => '拉取成功,返回消息页面',
        400 => '项目不存在|未设置投资喜好|不能重复拉取',
        422 => '项目主键必须',
        500 => '服务器错误',
    ];

    public function run(&$request)
    {
        $projectId  = $request->post('project_id/d',0);

        if (0 == $projectId) return [422,'项目主键必须'];

        // 检查项目是否存在
        $project = Db::name('project')->where('id',$projectId)->find();
        if ( is_null($project) ) return [400,'项目不存在'];

        // 检查投资人是否设置投资喜好
        $ret = Db::name('member_like')->where( 'member_id',Session::get('member.id') )->find();
        if ( empty($ret['round']) ) return [400,'未设置投资喜好'];

        // 投递人信息
        $fromMemberInfo = Db::name('member_info')->where('member_id',$project['member_id'])->find();
        $from['from_member_id']         = $fromMemberInfo['member_id'];
        $from['from_mobile']            = $fromMemberInfo['mobile'];
        $from['from_member_nickname']   = $fromMemberInfo['nickname'];
        $from['from_member_headimgurl'] = $fromMemberInfo['headimgurl'];
        
        // 接收者信息
        $toMemberInfo = Db::name('member_info')->where( 'member_id',Session::get('member.id') )->find();
        $to['to_member_id']             = $toMemberInfo['member_id'];
        $to['to_mobile']                = $toMemberInfo['mobile'];
        $to['to_member_nickname']       = $toMemberInfo['nickname'];
        $to['to_member_headimgurl']     = $toMemberInfo['headimgurl'];

        // 判断消息是否已经存在
        $ret = Db::name('project_push')->where('project_id',$projectId)->where('to_member_id',$to['to_member_id'])->find();
        if ( !is_null($ret) ) return [400,'不能重复拉取'];
        
        // 拉取消息
        $data['project_id']             = $projectId;
        $data['from_member_id']         = $from['from_member_id'];
        $data['from_mobile']            = $from['from_mobile'];
        $data['from_member_nickname']   = $from['from_member_nickname'];
        $data['from_member_headimgurl'] = $from['from_member_headimgurl'];
        $data['to_member_id']           = $to['to_member_id'];
        $data['to_mobile']              = $to['to_mobile'];
        $data['to_member_nickname']     = $to['to_member_nickname'];
        $data['to_member_headimgurl']   = $to['to_member_headimgurl'];
        $data['is_read']                = 1;
        $data['is_chat']                = 1;
        $data['create_time']            = time();
        $num = Db::name('project_push')->insert($data);

        return ($num > 0) ? [ 201,[] ] : 500;
    }
}